

from django.db.models import Sum
from decimal import Decimal
from django.db.models import Q, F
import requests
import json
from apps.common.utils.decrypt import *
from apps.merchant.item.dao import ItemDao
from apps.merchant.sku.dao import SkuDao
from apps.interface.client.dao import ClientDao
from apps.user.dao import UserDao
from apps.interface.advert.dao import AdvertDao
from apps.pay.order.dao import OrderDao
from django.core.exceptions import ValidationError


def replaceImageUrl():
    clients = ClientDao().findAll()
    print('items', clients.count())
    for item in clients:
        string = item.updateUrlForAndriod
        new_string = string.replace('zjyh.service.qly.plus', 'yhzb.service.zjyh888.com')
        item.updateUrlForAndriod = new_string

        if item.notify_url:
            string1 = item.notify_url
            new_string1 = string1.replace('zjyh.service.qly.plus', 'yhzb.service.zjyh888.com')
            item.notify_url = new_string1

        if item.logo:
            string2 = item.logo
            new_string2 = string2.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
            item.logo = new_string2

        if item.miniproUrl:
            string3 = item.miniproUrl
            new_string3 = string3.replace('zjyh.service.qly.plus', 'yhzb.service.zjyh888.com')
            item.miniproUrl = new_string3

        if item.baseUrl:
            string4 = item.baseUrl
            new_string4 = string4.replace('zjyh.service.qly.plus', 'yhzb.service.zjyh888.com')
            item.baseUrl = new_string4

        item.save()

    items = ItemDao().findAll().exclude(detaiΩlPhotosRichText='')
    print('items', items.count())
    for item in items:
        detailPhotosRichTextstr = item.detailPhotosRichText
        print('111', detailPhotosRichTextstr)
        new_string = detailPhotosRichTextstr.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        print('222', new_string)
        item.detailPhotosRichText = new_string

        coverPhotos = item.coverPhotos
        coverPhotos = coverPhotos.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        print('222', coverPhotos)
        item.coverPhotos = coverPhotos
        item.save()

    skus = SkuDao().findAll()
    for item in skus:
        coverUrl = item.coverUrl
        coverUrl = coverUrl.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        item.coverUrl = coverUrl

        item.save()

    users = UserDao().findAll()
    for item in users:
        avatarUrl = item.avatarUrl
        avatarUrl = avatarUrl.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        item.avatarUrl = avatarUrl
        item.save()

    adverts = AdvertDao().findAll()
    for item in adverts:
        coverUrl = item.coverUrl
        coverUrl = coverUrl.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        item.coverUrl = coverUrl
        item.save()

    orders = OrderDao().findAllMainOrder()
    for item in orders:
        content = item.content
        content = content.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        item.content = content
        item.save()

def handleItem6():
    for item in ItemDao().findAll():
        skus = item.item_sku.all()
        # print('skus', skus.count())
        sellingPrice = 0
        if skus.count() > 1:
            sellingPrice = skus.first().sellingPrice
            
            for sku in skus:
                print('多sku，价格', item.id, sku.sellingPrice)
            #     if sku.sellingPrice != sellingPrice:
            #         print('多sku，价格不同', item.id, sku.sellingPrice)
            # print('item', item.name)
        print('-------------------------')


def handleItem5():
    ItemDao().findAll().filter(Q(cate=7) | Q(cate=8) | Q(cate=9)| Q(cate=10)).update(cate=11)

def handleItem4():
    _skus = SkuDao().findAll().filter(coverUrl='')
    print('_skus', _skus.count())
    try:
        for sku in _skus:
            print('sku.coverUrl', sku.coverUrl)
            if not sku.coverUrl or sku.coverUrl != None:
                coverPhotoList = []
                if sku.item:
                    print('sku.item.coverPhotos', sku.item.coverPhotos)
                    coverPhotoList = json.loads(sku.item.coverPhotos)
                if len(coverPhotoList) > 0:
                    sku.coverUrl = coverPhotoList[0]
                    sku.save()
    except Exception as e:
        print('e', e)

def handleItem3():
    url = 'http://127.0.0.1:8001/api/merchant/itemForM/'
    headers = {'content-type': "application/json", 'Authorization': 'token bc1a7cb317256400d7e2fcf7c2e019a177f3f94b'}
    params = {
        'openshop': 17,
        'size': 1000,
        'isSingleSpec': 0
    }
    res = requests.get(url, params=params, headers=headers)
    resDict = json.loads(res.content)
    res = aesDecrypt(AESKey, resDict)
    _list = res.get('list')
    # print('拉取商品', res)
    # print('item', len(_list))
    for item in _list:
        _items = ItemDao().findAll().filter(name=item.get('itemName'))
        print('items个数', _items.count())
        print('skuList', item.get('skuList'))
        for sku in item.get('skuList'):
            skuData = {}
            skuData['specValues'] = sku.get('specValues')
            skuData['coverUrl'] = sku.get('cover')
            skuData['marketPrice'] = sku.get('marketPrice')
            skuData['sellingPrice'] = sku.get('sellingPrice')
            skuData['stock'] = '999'
            skuData['item'] = _items.first().id
            SkuDao().create(skuData)

    _items = ItemDao().findAll().filter(item_sku__isnull=True)
    for item in _items:
        print('产品名称', item.name)
        _skus = SkuDao().findAll().filter(item=item)
        print('_skus', _skus.count())
    print('_items', _items.count())




def handleItem2():
    # url = 'https://axh.service.sailami.top/api/merchant/itemForM/'
    url = 'http://127.0.0.1:8001/api/merchant/itemForM/'
    headers = {'content-type': "application/json", 'Authorization': 'token bc1a7cb317256400d7e2fcf7c2e019a177f3f94b'}
    params = {
        'openshop': 17,
        'size': 1000,
        'isSingleSpec': 0
    }
    res = requests.get(url, params=params, headers=headers)
    resDict = json.loads(res.content)
    res = aesDecrypt(AESKey, resDict)
    _list = res.get('list')
    print('拉取商品', res)
    print('item', _list[0])
    for item in _list:
        data = {}
        data['name'] = item.get('itemName')

        if item.get('shopinCate'):
            if item.get('shopinCate') == 71:
                data['cate'] = 7
            elif item.get('shopinCate') == 72:
                data['cate'] = 8
            elif item.get('shopinCate') == 73:
                data['cate'] = 9
            elif item.get('shopinCate') == 74:
                data['cate'] = 10
            elif item.get('shopinCate') == 75:
                data['cate'] = 11
        data['status'] = 1
        data['checkStatus'] = 'PASS'
        data['isOnlinePay'] = 1
        data['isSingleSpec'] = item.get('isSingleSpec')
        covers = item.get('coverPhotoList')
        coverUrls = []
        for file in covers:
            coverUrls.append(file.get('coverUrl'))
        data['coverPhotos'] = json.dumps(coverUrls)
        if item.get('detailPhotosRichText'):
            data['detailPhotosRichText'] = item.get('detailPhotosRichText')
        else:
            print('detailPhotoList')
            _files = item.get('detailPhotoList')
            detailstr = ''
            for file in _files:
                detailstr + '<img src="' + file.get('coverUrl') + '">'
            data['detailPhotosRichText'] = '<p>' + detailstr + '</p>'
        itemobj = ItemDao().create(data)
        if item.get('isSingleSpec') == 1:
            skuData = {}
            skuData['specValues'] = '[{"specName":"规格","name":"默认"}]'
            skuData['coverUrl'] = item.get('coverUrl')
            skuData['marketPrice'] = item.get('marketPrice')
            skuData['sellingPrice'] = item.get('sellingPrice')
            skuData['stock'] = item.get('totalStock') if item.get('totalStock')!='0' else '999'
            skuData['item'] = itemobj.id
            print('skuData', skuData)
            SkuDao().create(skuData)
        else:
            for sku in item.get('skuList'):
                skuData = {}
                skuData['specValues'] = sku.get('specValues')
                skuData['coverUrl'] = sku.get('coverUrl')
                skuData['marketPrice'] = sku.get('marketPrice')
                skuData['sellingPrice'] = sku.get('sellingPrice')
                skuData['stock'] = sku.get('stock') if sku.get('stock')!='0' else '999'
                skuData['item'] = itemobj.id
                SkuDao().create(skuData)
def handleItem1():
    _items = ItemDao().findAll().filter(cate__isnull=True)
    _items = _items.filter(name__contains='兔年金币')
    for item in _items:
        print('产品名称', item.name)
        # print('产品分类', item.cate)
    print('_items', _items.count())
    # _items.update(cate=12)